package 力扣;

import javax.sound.midi.Soundbank;

/**
 * @author yyq
 * @create 2022-03-10 9:56
 */
public class mst0207 {
    public static void main(String[] args) {
        ListNode headA=new ListNode(1);
        headA.next= new ListNode(2);
        ListNode headB=new ListNode(3);
        headB.next=headA.next;
        getIntersectionNode(headA,headB);
    }
    public static ListNode getIntersectionNode2(ListNode headA, ListNode headB) {
        ListNode tempA=headA;
        ListNode tempB=headB;
        while(tempA!=tempB){
            if(tempA.next!=null) tempA=tempA.next;
            else tempA=headB;
            if(tempB.next!=null) tempB=tempB.next;
            else tempB=headA;
        }
        return tempA;
    }
    public static ListNode getIntersectionNode(ListNode headA, ListNode headB) {
        if(headA==null||headB==null) return null;
        if(headA==headB) return headA;
        ListNodeMST Ahead=reverseList(headA);
        ListNodeMST Bhead=reverseList(headB);
        if(Ahead.val!=Bhead.val) return null;
        while (Ahead.val==Bhead.val){
            if(Ahead.next!=null&&Bhead.next!=null&&Ahead.next.val==Bhead.next.val){
                Ahead=Ahead.next;
                Bhead=Bhead.next;
            }
            else {
                System.out.println("Intersected at '"+Ahead.val.val+"'");
                return Ahead.val;
            }
        }
        return null;
    }
    public static ListNodeMST reverseList(ListNode head){
        ListNodeMST Ahead=null;
        ListNode temp=head;
        while(temp!=null){
            Ahead=new ListNodeMST(temp,Ahead);
            temp=temp.next;
        }
        return Ahead;
    }

}
class ListNodeMST {
    ListNode val;
    ListNodeMST next;
    ListNodeMST() {}

    public ListNodeMST(ListNode val, ListNodeMST next) {
        this.val = val;
        this.next = next;
    }
}
